<?php
if (!defined('SMF'))
	die('Hacking attempt...');

global $smcFunc, $txt, $scripturl, $boarddir;
global $dbtables;

$command = (isset($_POST['command'])) ? $_POST['command'] : '';


// Main Menu
if (empty($command))
{
	echo '<h4>Welcome to the BlackNova Traders Xenobe Control module</h4>
	<p>Select a function from the list below:</p>
	<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=xenobe_control" method="post">
		<select name="command">
			<option value="instruct">Xenobe Instructions</option>
			<option value="xenobeedit" selected>Edit a Xenobe Character</option>
			<option value="createnew">Create A New Xenobe Character</option>
			<option value="clearlog">Clear All Xenobe Log Files</option>
			<option value="clearxenobe">Clear Xenobe Database</option>
		</select>
		<input type="submit" value="Submit" />
	</form>';
}
else
{
	if ($command == "instruct")
	{
		echo '
		<h2>Xenobe Instructions</H2>
		<p>Welcome to the Xenobe Control module.  This is the module that will control the Xenobe players in the game.  
		It is very simple right now, but will be expanded in future versions.  
		The ultimate goal of the Xenobe players is to create some interactivity for those games without a large user base.  
		I need not say that the Xenobe will also make good cannon fodder for those games with a large user base.</p>

		<h3>Xenobe Creation</h3>
		<p>In order to create a Xenobe you must choose the <strong>"Create A Xenobe Character"</strong> option from the menu.  
		This will bring up the Xenobe character creation screen.  There are only a few fields for you to edit.  
		However, with these fields you will determine not only how your Xenobe will be created, but how he will act in the game.  
		We will now go over these fields and what they will do.</p>

		<p>When creating a new Xenobe character the <strong>Xenobe Name</strong> and the <strong>Shipname</strong> are automatically generated.  
		You can change these default values by editing these fields before submitting the character for creation.  
		Take care not to duplicate a current player or ship name, for that will result in creation failure.</p>
		
		<p>The starting <strong>Sector</strong> number will also be randomly generated.  
		You can change this to any sector.  However, you should take care to use a valid sector number. Otherwise the creation will fail.</p>
		
		<p>The <strong>Level</strong> field will default to "3".  This field refers to the starting tech level of all ship stats.  
		So a default Xenobe will have it\'s Hull, Beams, Power, Engine, etc... all set to 3 unless this value is changed.  
		All appropriate ship stores will be set to the maximum allowed by the given tech level.  
		So, starting levels of energy, fighters, armor, torps, etc... are all affected by this setting.</p>
		
		<p>The <strong>Active</strong> checkbox will default to checked.  
		This box refers to if the Xenobe AI system will see this Xenobe and execute it\'s orders.  
		If this box is not checked then the Xenobe AI system will ignore this record and the next two fields are ignored.</p>
		
		<p>The <strong>Orders</strong> selection box will default to "Sentinel".  
		There are three other options available: "Roam", "Roam and Trade", and "Roam and Hunt".  
		These Orders and what they mean will be detailed below.</p>
		
		<p>The <strong>Aggression</strong> selection box will default to "Peaceful".  
		There are two other options available: "Attack Sometimes", and "Attack Always".  
		These Aggression settings and what they mean will be detailed below.</p>
		
		<p>Pressing the <strong>Create</strong> button will create the Xenobe and return to the creation screen to create another.</p>

		<h3>Xenobe Orders</h3>
		
		<p>Here are the Xenobe Order options and what the Xenobe AI system will do for each:</p>
		
		<ul>
			<li><strong>Sentinel</strong></li>
			<li>This Xenobe will stay in place.  His only interactions will be with those who are in his sector at the time he takes his turn.  
			The aggression level will determine what those player interactions are.</li>
			<li><strong>Roam</strong></li>
			<li>This Xenobe will warp from sector to sector looking for players to interact with.  
			The aggression level will determine what those player interactions are.</li>
			<li><strong>Roam and Trade</strong></li>
			<li>This Xenobe will warp from sector to sector looking for players to interact with and ports to trade with.  
			The Xenobe will trade at a port if possible before looking for player interactions.  
			The aggression level will determine what those player interactions are.</li>
			<li><strong>Roam and Hunt</strong></li>
			<li>This Xenobe has a taste for blood and likes the sport of a good hunt.  
			Ocassionally (around 1/4th the time) this Xenobe has the urge to go hunting.  He will randomly choose one of the top ten players to hunt.  
			If that player is in a sector that allows attack, then the Xenobe warps there and attacks.
			When he is not out hunting this Xenobe acts just like one with ROAM orders.</li>
		</ul>
		
		<h3>Xenobe Aggression</h3>
		
		<p>Here are the Xenobe Aggression levels and what the Xenobe AI system will do for each:</p>
		
		<ul>
			<li><strong>Peaceful</strong></li>
			<li>This Xenobe will not attack players.  He will continue to roam or trade as ordered but will not launch any attacks.
			If this Xenobe is a hunter then he will still attack players on the hunt but never otherwise.</li>
			<li><strong>Attack Sometimes</strong></li>
			<li>This Xenobe will compare it\'s current number of fighters to a players fighters before deciding to attack.
			If the Xenobe\'s fighters are greater then the player\'s, then the Xenobe will attack the player.</li>
			<li><strong>Attack Always</strong></li>
			<li>This Xenobe is just mean.  He will attack anyone he comes across regardless of the odds.</li>
		</ul>';
    }
    elseif ($command == "xenobeedit")
    {
		$ship_id = (isset($_POST['ship_id'])) ? $_POST['ship_id'] : '';
		
		echo '
			<h3>Xenobe Editor</h3>
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=xenobe_control" method="post">';
		
		if (empty($ship_id))
		{
			echo '
				<select size="10" name="ship_id">';
				
			$result = $smcFunc['db_query']('', '
				SELECT {raw:db_ships}.ship_id, {raw:db_ships}.character_name, {raw:db_ships}.ship_destroyed, {raw:db_ships}.sector, {raw:db_xenobes}.active
				FROM {raw:db_ships}
				LEFT JOIN {raw:db_xenobes} ON {raw:db_xenobes}.ship_id = {raw:db_ships}.ship_id
				WHERE {raw:db_ships}.xenobe = "Y"',
				array(
					'db_ships' => $dbtables['ships'],
					'db_xenobes' => $dbtables['xenobes'],
				)
			);

			while ($row = $smcFunc['db_fetch_assoc']($result))
			{
				$character_name = '[' . $row['character_name'] . ']';
				$sector = '[' . $row['sector'] . ']';
				
				if ($row['active'] == "Y")
					$activelist = "[Active - Y]";
				else
					$activelist = "[Active - N]";
				
				if ($row['ship_destroyed'] == "Y")
					$destroylist = "[Destroyed - Y]";
				else
					$destroylist = "[Destroyed - N]";
					
				printf ('<option value="%s">%s %s %s %s</option>', $row['ship_id'], $character_name, $sector, $activelist, $destroylist);
			}
			
			$smcFunc['db_free_result']($result);
			
			echo '
				</select>
				<input type="hidden" name="command" value="xenobeedit" />
				<input type="submit" value="Edit" />';
		}
		else
		{
			$operation = (isset($_POST['operation'])) ? $_POST['operation'] : '';
			
			if (empty($operation))
			{
				$ship_id = (isset($_POST['ship_id'])) ? $_POST['ship_id'] : '';
				
				$result = $smcFunc['db_query']('', '
					SELECT *
					FROM {raw:db_ships}
					LEFT JOIN {raw:db_xenobes} ON {raw:db_xenobes}.ship_id = {raw:db_ships}.ship_id
					WHERE {raw:db_ships}.ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'db_xenobes' => $dbtables['xenobes'],
						'ship_id' => $ship_id,
					)
				);
				$row = $smcFunc['db_fetch_assoc']($result);
				$smcFunc['db_free_result']($result);

				echo '
					<table border="0" cellspacing="0" cellpadding="5">
					<tbody>
						<tr>
							<td>Xenobe Name</td>
							<td><input type="text" name="character_name" value="', $row['character_name'], '" /></td>
						</tr>
						<tr>
							<td>Active</td>
							<td><input type="checkbox" name="active" value="on" ', checked($row['active']), ' /></td>
						</tr>
						<tr>
							<td>Id</td>
							<td>', $row['ship_id'], '</td>
						</tr>
						<tr>
							<td>Ship Name</td>
							<td><input type="text" name="ship_name" value="', $row['ship_name'], '"></td>
						</tr>
						<tr>
							<td>Destroyed</td>
							<td><input type="checkbox" name="ship_destroyed" value="on" ', checked($row['ship_destroyed']), '></td>
						</tr>
						<tr>
							<td>Orders</td>
							<td>
								<select size="1" name="orders">';
				
				$oorder0 = $oorder1 = $oorder2 = $oorder3 = 'value';
				if ($row['orders'] == 0)
					$oorder0 = 'selected="0" value';
				if ($row['orders'] == 1)
					$oorder1 = 'selected="1" value';
				if ($row['orders']  == 2)
					$oorder2 = 'selected="2" value';
				if ($row['orders']  == 3)
					$oorder3 = 'selected="3" value';
					
				echo '
									<option "', $oorder0, '="0">Sentinel</option>
									<option "', $oorder1, '="1">Roam</option>
									<option "', $oorder2, '="2">Roam and Trade</option>
									<option "', $oorder3, '="3">Roam and Hunt</option>
								</select>
							</td>
						</tr>
						<tr>
							<td>Aggression</td>
							<td>';
							
				$oaggr0 = $oaggr1 = $oaggr2 = 'value';
				if ($row['aggression'] == 0)
					$oaggr0 = 'selected="0" value';
				if ($row['aggression'] == 1)
					$oaggr1 = 'selected="1" value';
				if ($row['aggression'] == 2)
					$oaggr2 = 'selected="2" value';
				
				echo '
								<select size="1" name="aggression">
									<option ', $oaggr0, '="0">Peaceful</option>
									<option ', $oaggr1, '="1">Attack Sometimes</option>
									<option ', $oaggr2, '="2">Attack Always</option>
								</select>
							</td>
						</tr>
						<tr>
							<td>Levels</td>
							<td>
								<table border="0" cellspacing="0" cellpadding="5">
									<tr>
										<td>Hull</td>
										<td><input type="text" size="5" name="hull" value="', $row['hull'], '" /></td>
										<td>Engines</td>
										<td><input type="text" size="5" name="engines" value="', $row['engines'], '" /></td>
										<td>Power</td>
										<td><input type="text" size="5" name="power" value="', $row['power'] ,'" /></td>
										<td>Computer</td>
										<td><input type="text" size="5" name="computer" value="', $row['computer'] ,'" /></td>
									</tr>
									<tr>
										<td>Sensors</td>
										<td><input type="text" size="5" name="sensors" value="', $row['sensors'], '"></td>
										<td>Armour</td>
										<td><input type="text" size="5" name="armor" value="', $row['armor'], '"></td>
										<td>Shields</td>
										<td><input type="text" size="5" name="shields" value="', $row['shields'], '"></td>
										<td>Beams</td>
										<td><input type="text" size="5" name="beams" value="', $row['beams'], '"></td>
									</tr>
									<tr>
										<td>Torpedoes</td>
										<td><input type="text" size="5" name="torp_launchers" value="', $row['torp_launchers'], '"></td>
										<td>Cloak</td>
										<td><input type="text" size="5" name="cloak" value="', $row['cloak'], '"></td>
									</tr>
								</table>
							</td>
						</tr>
						<tr>
							<td>Holds</td>
							<td>
								<table border="0" cellspacing="0" cellpadding="5">
									<tr>
										<td>Ore</td>
										<td><input type="text" size="8" name="ship_ore" value="', $row['ship_ore'], '"></td>
										<td>Organics</td>
										<td><input type="text" size="8" name="ship_organics" value="', $row['ship_organics'] ,'"></td>
										<td>Goods</td>
										<td><input type="text" size="8" name="ship_goods" value="', $row['ship_goods'], '"></td>
									</tr>
									<tr>
										<td>Energy</td>
										<td><input type="text" size="8" name="ship_energy" value="', $row['ship_energy'], '"></td>
										<td>Colonists</td>
										<td><input type="text" size="8" name="ship_colonists" value="', $row['ship_colonists'], '"></td>
									</tr>
								</table>
							</td>
						</tr>
						<tr>
							<td>Combat</td>
							<td>
								<table border="0" cellspacing="0" cellpadding="5">
									<tr>
										<td>Fighters</td>
										<td><input type="text" size="8" name="ship_fighters" value="', $row['ship_fighters'], '"></td>
										<td>Torpedoes</td>
										<td><input type="text" size="8" name="torps" value="', $row['torps'], '"></td>
									</tr>
									<tr>
										<td>Armour Pts</td>
										<td><input type="text" size="8" name="armor_pts" value="', $row['armor_pts'], '"></td>
									</tr>
								</TABLE>
							</td>
						</tr>
						<tr>
							<td>Devices</td>
							<td>
								<table border="0" cellspacing="0" cellpadding="5">
									<tr>
										<td>Beacons</td>
										<td><input type="text" size="5" name="dev_beacon" value="', $row['dev_beacon'], '"></td>
										<td>Warp Editors</td>
										<td><input type="text" size="5" name="dev_warpedit" value="', $row['dev_warpedit'], '"></td>
										<td>Genesis Torpedoes</td>
										<td><input type="text" size="5" name="dev_genesis" value="', $row['dev_genesis'], '"></td>
									</tr>
									<tr>
										<td>Mine Deflectors</td>
										<td><input type="text" size="5" name="dev_minedeflector" value="', $row['dev_minedeflector'], '"></td>
										<td>Emergency Warp</td>
										<td><input type="text" size="5" name="dev_emerwarp" value="', $row['dev_emerwarp'], '"></td>
									</tr>
									<tr>
										<td>Escape Pod</td>
										<td><input type=checkbox name="dev_escapepod" value="on" ', checked($row['dev_escapepod']), '></td>
										<td>FuelScoop</td>
										<td><input type=checkbox name="dev_fuelscoop" value="on" ', checked($row['dev_fuelscoop']), '></td>
									</tr>
								</table>
							</td>
						</tr>
						<tr>
							<td>Credits</td>
							<td><input type="text" name="credits" value="', $row['credits'], '"></td>
						</tr>
						<tr>
							<td>Turns</td>
							<td><input type="text" name="turns" value="', $row['turns'], '"></td>
						</tr>
						<tr>
							<td>Current sector</td>
							<td><input type="text" name="sector" value="', $row['sector'], '"></td>
						</tr>
				</table>
				<br />
				<input type="hidden" name="ship_id" value="', $ship_id, '" />
				<input type="hidden" name="operation" value="save" />
				<input type="hidden" name="command" value="xenobeedit" />
				<input type="submit" value="Save" />';
				

				// Show xenobe log data
				echo '
				<hr />
				<h3>Log Data For This Xenobe</h3>';
				
				$result = $smcFunc['db_query']('', '
					SELECT *
					FROM {raw:db_logs}
					WHERE ship_id = {int:ship_id}
					ORDER BY time DESC, type DESC',
					array(
						'db_logs' => $dbtables['logs'],
						'ship_id' => $ship_id,
					)
				);
				
				while($logrow = $smcFunc['db_fetch_assoc']($result))
				{
					$logtype = "";
					switch($logrow['type'])
					{
						case LOG_XENOBE_ATTACK:
							$logtype = "Launching an attack on ";
							break;
						case LOG_ATTACK_LOSE:
							$logtype = "We were attacked and lost against ";
							break;
						case LOG_ATTACKED_WIN:
							$logtype = "We were attacked and won against ";
						break;
					}
					echo '
						<p> ', $logrow['time'], ' ', $logtype, ' ', $logrow['data'], '</p>';
				}
			}
			elseif ($operation == "save")
			{
				// Read all the request variables from the xenobe edit form
				$ship_id = (isset($_POST['ship_id'])) ? $_POST['ship_id'] : '';
				$character_name = (isset($_POST['character_name'])) ? $_POST['character_name'] : '';
				$ship_name = (isset($_POST['ship_name'])) ? $_POST['ship_name'] : '';
				$ship_destroyed = (isset($_POST['ship_destroyed'])) ? 'Y' : 'N';
				$hull = (isset($_POST['hull'])) ? $_POST['hull'] : '';
				$engines = (isset($_POST['engines'])) ? $_POST['engines'] : '';
				$power = (isset($_POST['power'])) ? $_POST['power'] : '';
				$computer = (isset($_POST['computer'])) ? $_POST['computer'] : '';
				$sensors = (isset($_POST['sensors'])) ? $_POST['sensors'] : '';
				$armor = (isset($_POST['armor'])) ? $_POST['armor'] : '';
				$shields = (isset($_POST['shields'])) ? $_POST['shields'] : '';
				$beams = (isset($_POST['beams'])) ? $_POST['beams'] : '';
				$torp_launchers = (isset($_POST['torp_launchers'])) ? $_POST['torp_launchers'] : '';
				$cloak = (isset($_POST['cloak'])) ? $_POST['cloak'] : '';
				$credits = (isset($_POST['credits'])) ? $_POST['credits'] : '';
				$turns = (isset($_POST['turns'])) ? $_POST['turns'] : '';
				$dev_warpedit = (isset($_POST['dev_warpedit'])) ? $_POST['dev_warpedit'] : '';
				$dev_genesis = (isset($_POST['dev_genesis'])) ? $_POST['dev_genesis'] : '';
				$dev_beacon = (isset($_POST['dev_beacon'])) ? $_POST['dev_beacon'] : '';
				$dev_emerwarp = (isset($_POST['dev_emerwarp'])) ? $_POST['dev_emerwarp'] : '';
				$dev_escapepod = (isset($_POST['dev_escapepod'])) ? 'Y' : 'N';
				$dev_fuelscoop = (isset($_POST['dev_fuelscoop'])) ? 'Y' : 'N';
				$dev_minedeflector = (isset($_POST['dev_minedeflector'])) ? $_POST['dev_minedeflector'] : '';
				$sector = (isset($_POST['sector'])) ? $_POST['sector'] : '';
				$ship_ore = (isset($_POST['ship_ore'])) ? $_POST['ship_ore'] : '';
				$ship_organics = (isset($_POST['ship_organics'])) ? $_POST['ship_organics'] : '';
				$ship_goods = (isset($_POST['ship_goods'])) ? $_POST['ship_goods'] : '';
				$ship_energy = (isset($_POST['ship_energy'])) ? $_POST['ship_energy'] : '';
				$ship_colonists = (isset($_POST['ship_colonists'])) ? $_POST['ship_colonists'] : '';
				$ship_fighters = (isset($_POST['ship_fighters'])) ? $_POST['ship_fighters'] : '';
				$torps = (isset($_POST['torps'])) ? $_POST['torps'] : '';
				$armor_pts = (isset($_POST['armor_pts'])) ? $_POST['armor_pts'] : '';
				$active = (isset($_POST['active'])) ? 'Y' : 'N';
				$aggression = (isset($_POST['aggression'])) ? $_POST['aggression'] : '';
				$orders = (isset($_POST['orders'])) ? $_POST['orders'] : '';
				
				// Update database
				$smcFunc['db_query']('', '
					UPDATE {raw:db_ships}
					SET character_name = {string:character_name},
						ship_name = {string:ship_name},
						ship_destroyed = {string:ship_destroyed},
						hull = {int:hull},
						engines = {int:engines},
						power = {int:power},
						computer = {int:computer},
						sensors = {int:sensors},
						armor = {int:armor},
						shields = {int:shields},
						beams = {int:beams},
						torp_launchers = {int:torp_launchers},
						cloak = {int:cloak},
						credits = {int:credits},
						turns = {int:turns},
						dev_warpedit = {int:dev_warpedit},
						dev_genesis = {int:dev_genesis},
						dev_beacon = {int:dev_beacon},
						dev_emerwarp = {int:dev_emerwarp},
						dev_escapepod = {string:dev_escapepod},
						dev_fuelscoop = {string:dev_fuelscoop},
						dev_minedeflector = {int:dev_minedeflector},
						sector = {int:sector},
						ship_ore = {int:ship_ore},
						ship_organics = {int:ship_organics},
						ship_goods = {int:ship_goods},
						ship_energy = {int:ship_energy},
						ship_colonists = {int:ship_colonists},
						ship_fighters = {int:ship_fighters},
						torps = {int:torps},
						armor_pts = {int:armor_pts}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_ships' => $dbtables['ships'],
						'ship_id' => $ship_id,
						'character_name' => $character_name,
						'ship_name' => $ship_name,
						'ship_destroyed' => $ship_destroyed,
						'hull' => $hull,
						'engines' => $engines,
						'power' => $power,
						'computer' => $computer,
						'sensors' => $sensors,
						'armor' => $armor,
						'shields' => $shields,
						'beams' => $beams,
						'torp_launchers' => $torp_launchers,
						'cloak' => $cloak,
						'credits' => $credits,
						'turns' => $turns,
						'dev_warpedit' => $dev_warpedit,
						'dev_genesis' => $dev_genesis,
						'dev_beacon' => $dev_beacon,
						'dev_emerwarp' => $dev_emerwarp,
						'dev_escapepod' => $dev_escapepod,
						'dev_fuelscoop' => $dev_fuelscoop,
						'dev_minedeflector' => $dev_minedeflector,
						'sector' => $sector,
						'ship_ore' => $ship_ore,
						'ship_organics' => $ship_organics,
						'ship_goods' => $ship_goods,
						'ship_energy' => $ship_energy,
						'ship_colonists' => $ship_colonists,
						'ship_fighters' => $ship_fighters,
						'torps' => $torps,
						'armor_pts' => $armor_pts,
					)
				);
				
				$smcFunc['db_query']('', '
					UPDATE {raw:db_xenobes}
					SET active = {string:active},
						aggression = {int:aggression},
						orders = {int:orders}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_xenobes' => $dbtables['xenobes'],
						'ship_id' => $ship_id,
						'active' => $active,
						'aggression' => $aggression,
						'orders' => $orders,
					)
				);
				
				echo '
					<p>Changes to Xenobe activity record have been saved.</p>';
			}
			else
				echo '
					<p>Invalid operation</p>';
		}
		echo '
			<input type="hidden" name="menu" value="xenobeedit" />
			</form>';
    }
    elseif ($command == "clearxenobe")
    {
		$operation = (isset($_POST['operation'])) ? $_POST['operation'] : '';
		
		echo '
			<h3>Clear Xenobe Database</h3>
			<p>This will DELETE All Xenobe records from the <em>ships</em> table.</p>
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=xenobe_control" method="post">';
			
		if (empty($operation))
		{
			echo '
				<p>Are you sure?</p>
				<input type="hidden" name="operation" value="dropxen">
				<input type="submit" value="Clear">';
		}
		elseif ($operation == "dropxen")
		{
			// Delete all xenobe in the ships table
			echo '
				<p>Deleting xenobe records in the ships table . . .</p>';
			
			$result = $smcFunc['db_query']('', '
				SELECT ship_id
				FROM {raw:db_ships}
				WHERE xenobe = "Y"',
				array(
					'db_ships' => $dbtables['ships'],
				)
			);
			
			while ($row = $smcFunc['db_fetch_assoc']($result))
			{
				db_kill_player($row['ship_id'],true);
			}
			
			$smcFunc['db_query']('', '
				DELETE FROM {raw:db_ships}
				WHERE xenobe = "Y"',
				array(
					'db_ships' => $dbtables['ships'],
				)
			);
			
			$smcFunc['db_query']('', '
				DELETE FROM {raw:db_xenobes}',
				array(
					'db_xenobes' => $dbtables['xenobes'],
				)
			);
		}
		else
			echo 'Invalid operation';
			
		echo '
				<input type="hidden" name="command" value="clearxenobe" />
			</form>';
    }
    elseif ($command == "clearlog")
    {
		$operation = (isset($_POST['operation'])) ? $_POST['operation'] : '';
		
		echo '
			<h3>Clear All Xenobe Logs</h3>
			<p>This will DELETE All Xenobe log files</p>
			<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=xenobe_control" method="post">';
		
		if (empty($operation))
		{
			echo '
			<p>Are you sure?</p>
			<input type="hidden" name="operation" value="clearxenlog">
			<input type="submit" value="Clear">';
		}
		elseif ($operation == "clearxenlog")
		{
			$result = $smcFunc['db_query']('', '
				SELECT ship_id
				FROM {raw:db_ships}
				WHERE xenobe = "Y"',
				array(
					'db_ships' => $dbtables['ships'],
				)
			);
			
			while ($row = $smcFunc['db_fetch_assoc']($result))
			{
				$smcFunc['db_query']('', '
					DELETE FROM {raw:db_logs}
					WHERE ship_id = {int:ship_id}',
					array(
						'db_logs' => $dbtables['logs'],
						'ship_id' => $row['ship_id'],
					)
				);
				
				echo '
					<p>Log for ship_id ', $row['ship_id'], ' cleared.</p>';
			}
			
			$smcFunc['db_free_result']($result);
		}
		else
			echo '
				<p>Invalid operation</p>';
				
		echo '
				<input type="hidden" name="command" value="clearlog" />
			</form>';
    }
    elseif ($command == "createnew")
    {
		global $sector_max;
		
		$operation = (isset($_POST['operation'])) ? $_POST['operation'] : '';
	
		echo '
			<h3>Create A New Xenobe</h3>';
			
		if (empty($operation))
		{
			// Create Xenobe Name
			$Syllable1 = array("Ak","Al","Ar","B","Br","D","F","Fr","G","Gr","K","Kr","N","Ol","Om","P","Qu","R","S","Z");
			$Syllable2 = array("a","ar","aka","aza","e","el","i","in","int","ili","ish","ido","ir","o","oi","or","os","ov","u","un");
			$Syllable3 = array("ag","al","ak","ba","dar","g","ga","k","ka","kar","kil","l","n","nt","ol","r","s","ta","til","x");
			$sy1roll = rand(0,19);
			$sy2roll = rand(0,19);
			$sy3roll = rand(0,19);
			$character = $Syllable1[$sy1roll] . $Syllable2[$sy2roll] . $Syllable3[$sy3roll];
			
			$result = $smcFunc['db_query']('', '
				SELECT character_name
				FROM {raw:db_ships}
				WHERE character_name = {string:character}',
				array(
					'db_ships' => $dbtables['ships'],
					'character' => $character,
				)
			);
			
			if ($smcFunc['db_num_rows']($result) == 0)
			{	
				// If Name Exists Try Again
				$i = 0;
				$namecheck = '';
				while (empty($namecheck) && $i < 100)
				{
					$sy1roll = rand(0,19);
					$sy2roll = rand(0,19);
					$sy3roll = rand(0,19);
					$character = $Syllable1[$sy1roll] . $Syllable2[$sy2roll] . $Syllable3[$sy3roll];
					
					$result = $smcFunc['db_query']('', '
						SELECT character_name
						FROM {raw:db_ships}
						WHERE character_name = {string:character}',
						array(
							'db_ships' => $dbtables['ships'],
							'character' => $character,
						)
					);
					
					if ($smcFunc['db_num_rows']($result) > 0)
					{
						$namecheck = $smcFunc['db_fetch_assoc']($result);
						$smcFunc['db_free_result']($result);
					}
					
					$i++;
				}
			}
			
			// Create Ship Name
			$shipname = "Xenobe-" . $character;
        
			// Select Random Sector
			$sector = rand(1,$sector_max - 1);
        
			// Display Confirmation Form
			echo '
				<form action="', $scripturl, '?action=admin;area=blacknovagame;sa=xenobe_control" method="post">
					<table border="0" cellspacing="0" cellpadding="5">
						<tbody>
							<tr>
								<td>Xenobe Name</td>
								<td><input type="text" size="20" name="character" value="', $character, '"></td>
								<td>Level <input type="text" size="5" name="xenlevel" value="3" /></td>
								<td>Ship Name <input type="text" size="20" name="shipname" value="', $shipname, '" /></td>
							</tr>
							<tr>
								<td>Active<input type="checkbox" name="active" value="on" checked /></td>
								<td>
									Orders 
									<select size="1" name="orders">
										<option selected="0" value="0">Sentinel</option>
										<option value="1">Roam</option>
										<option value="2">Roam and Trade</option>
										<option value="3">Roam and Hunt</option>
									</select>
								</td>
								<td>sector <input type="text" size="5" name="sector" value="', $sector, '" /></td>
								<td>
									Aggression 
									<select size="1" name="aggression">
										<option selected="0" value="0">Peaceful</option>
										<option value="1">Attack Sometimes</option>
										<option value="2">Attack Always</option>
									</select>
								</td>
							</tr>
						</tbody>
					</table>
					<input type="hidden" name="operation" value="createxenobe" />
					<input type="hidden" name="command" value="createnew" />
					<input type="Submit" value="Create" />
				</form>';
		}
		elseif ($operation == "createxenobe")
		{
			global $start_turns, $start_credits;
			
			$active = (isset($_POST['active'])) ? $_POST['active'] : '';
			$aggression = (isset($_POST['aggression'])) ? $_POST['aggression'] : '';
			$orders = (isset($_POST['orders'])) ? $_POST['orders'] : '';
			$shipname = (isset($_POST['shipname'])) ? $_POST['shipname'] : '';
			$xenlevel = (isset($_POST['xenlevel'])) ? $_POST['xenlevel'] : '';
			$character = (isset($_POST['character'])) ? $_POST['character'] : '';
			$sector = (isset($_POST['sector'])) ? $_POST['sector'] : '';
			
			// Update database
			$active = empty($active) ? "N" : "Y";
			$errflag = 0;
			
			if ($character == '' || $shipname == '')
			{
				echo '
					<p>Ship name and character name may not be blank.</p>';
				$errflag = 1;
			}
				
			if ($errflag == 0)
			{
				if ($xenlevel == '')
					$xenlevel=0;
				$maxenergy = NUM_ENERGY($xenlevel);
				$maxarmor = NUM_ARMOUR($xenlevel);
				$maxfighters = NUM_FIGHTERS($xenlevel);
				$maxtorps = NUM_TORPEDOES($xenlevel);
				$stamp = date("Y-m-d H:i:s");

				// Insert the new xenobe into the ships database
				$smcFunc['db_insert']('insert',
					$dbtables['ships'],
					array(
						'ship_name' => 'string',
						'ship_destroyed' => 'string',
						'character_name' => 'string',
						'hull' => 'int',
						'engines' => 'int',
						'power' => 'int',
						'computer' => 'int',
						'sensors' => 'int',
						'beams' => 'int',
						'torp_launchers' => 'int',
						'torps' => 'int',
						'shields' => 'int',
						'armor' => 'int',
						'armor_pts' => 'int',
						'cloak' => 'int',
						'credits' => 'int',
						'sector' => 'int',
						'ship_ore' => 'int',
						'ship_organics' => 'int',
						'ship_goods' => 'int',
						'ship_energy' => 'int',
						'ship_colonists' => 'int',
						'ship_fighters' => 'int',
						'turns' => 'int',
						'on_planet' => 'string',
						'dev_warpedit' => 'int',
						'dev_genesis' => 'int',
						'dev_beacon' => 'int',
						'dev_emerwarp' => 'int',
						'dev_escapepod' => 'string',
						'dev_fuelscoop' => 'string',
						'dev_minedeflector' => 'int',
						'last_login' => 'string',
						'trade_colonists' => 'string',
						'trade_fighters' => 'string',
						'trade_torps' => 'string',
						'trade_energy' => 'string',
						'dev_lssd' => 'string',
						'xenobe' => 'string',
					),
					array(
						$shipname,
						'N',
						$character,
						$xenlevel,
						$xenlevel,
						$xenlevel,
						$xenlevel,
						$xenlevel,
						$xenlevel,
						$xenlevel,
						$maxtorps,
						$xenlevel,
						$xenlevel,
						$maxarmor,
						$xenlevel,
						$start_credits,
						$sector,
						0,
						0,
						0,
						$maxenergy,
						0,
						$maxfighters,
						$start_turns,
						'N',
						0,
						0,
						0,
						0,
						'N',
						'N',
						0,
						$stamp,
						'N',
						'N',
						'N',
						'N',
						'N',
						'Y',
					),
					''
				);
				
				// Insert the new xenobe into the xenobe database
				$smcFunc['db_insert']('insert',
					$dbtables['xenobes'],
					array(
						'ship_id' => 'int',
						'active' => 'string',
						'aggression' => 'int',
						'orders' => 'int',
					),
					array(
						$smcFunc['db_insert_id']($dbtables['ships'], 'ship_id'),
						$active,
						$aggression,
						$orders,
					),
					''
				);
				
				echo '
					<p>Xenobe has been created.</p>
					<p>Xenobe records have been updated</p>';
			}
		}
		else
			echo '
					<p>Unknown operation</p>';
	}
}

function checked($yesno)
{
  return(($yesno == 'Y') ? 'CHECKED' : '');
}

function yesno($onoff)
{
  return(($onoff == 'ON') ? 'Y' : 'N');
}

?>